﻿using System;

namespace GMS.Framework.Utility.Operator
{
    public class OperatorProvider
    {
        public static OperatorProvider Provider
        {
            get { return new OperatorProvider(); }
        }

        private string LoginUserKey
        {
            get
            {
                return string.Format("{0}loginuser", KeyPrefix);
            }
        }

        private string LoginProvider = "Cookie";
        private string KeyPrefix
        {
            get
            {
                var urlHost = Fetch.ServerWholeDomain;
                var urlHostArray = urlHost.Split(new char[] { '.' });
                if ((urlHostArray.Length > 1) && !RegExp.IsIp(urlHost))
                {
                    urlHost = urlHost.Remove(urlHost.LastIndexOf(".", StringComparison.Ordinal));
                }
                var keyPrefixPre = urlHost.Replace('.', '_');
                return string.Format("{0}_HuiKaoBa_", keyPrefixPre);
            }
        }

        public OperatorModel GetCurrent()
        {
            var operatorModel = new OperatorModel();
            if (LoginProvider == "Cookie")
            {
                if (string.IsNullOrEmpty(Cookie.GetValue(LoginUserKey)))
                {
                    operatorModel = null;
                }
                else
                {
                    operatorModel = DESProvider.DecryptString(Cookie.GetValue(LoginUserKey)).ToObject<OperatorModel>();
                }
            }
            else
            {
                //operatorModel = DESProvider.EncryptString(WebHelper.GetSession(LoginUserKey).ToString()).ToObject<OperatorModel>();
            }
            return operatorModel;
        }
        public void AddCurrent(OperatorModel operatorModel)
        {
            if (LoginProvider == "Cookie")
            {
                Cookie.SaveWithMinute(LoginUserKey, DESProvider.EncryptString(operatorModel.ToJson()), 600);
            }
            else
            {
                //WebHelper.WriteSession(LoginUserKey, DESProvider.EncryptString(operatorModel.ToJson()));
            }
        }
        public void RemoveCurrent()
        {
            if (LoginProvider == "Cookie")
            {
                Cookie.Remove(LoginUserKey.Trim());
            }
            else
            {
                //WebHelper.RemoveSession(LoginUserKey.Trim());
            }
        }

    }
}
